package com.leshowski.agendaUCV2.twitter.control;

import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.conf.ConfigurationBuilder;

public class ManejaTwitter {
	
	private String consumerKey       = null;
	private String consumerSecret    = null;
	private String accessToken       = null;
	private String accessTokenSecret = null;
	
	private ConfigurationBuilder confBuilder = null;
	
	public ManejaTwitter(String consumerKey,
				   		String consumerSecret,
				   		String accessToken,
				   		String accessTokenSecret){
		
		this.consumerKey       = consumerKey;
		this.consumerSecret    = consumerSecret;
		this.accessToken       = accessToken;
		this.accessTokenSecret = accessTokenSecret;
		
	}
	
	public void publicaTweet(String mensaje) throws Exception{

		try{
			
			Twitter twitter = null;
			
			twitter = obtieneInstanciaTwitter();
		    
			try{
				
				Status status = null;
				status = twitter.updateStatus(mensaje);
				
			}catch(TwitterException e){
			
				boolean publicado = false;
				
				if(e.getExceptionCode()!= null && e.getExceptionCode().equals("b2b52c28-1c67fec4"))
					publicado = true;
				
				if(!publicado)
			    	throw e;
			}
			
		}catch(Exception e){
			throw e;
		}
	}
	
	public Twitter obtieneInstanciaTwitter() throws Exception{
		
		Twitter twitter = null;
		
		try{
			
			//Se verifican variables nulas
			if(this.consumerKey ==null)
				throw new NullPointerException("consumerKey");
			if(this.consumerSecret == null) 
				throw new NullPointerException("consumerSecret");
			if(this.accessToken == null)   
				throw new NullPointerException("accessToken");
			if(this.accessTokenSecret == null)
				throw new NullPointerException("accessTokenSecret");
			
			confBuilder  = new ConfigurationBuilder();
			
			confBuilder.setOAuthAccessToken(accessToken)
			.setOAuthAccessTokenSecret(accessTokenSecret)
			.setOAuthConsumerKey(consumerKey)
			.setOAuthConsumerSecret(consumerSecret);

			twitter = new TwitterFactory(confBuilder.build()).getInstance(); 
			
			return twitter;
			
		}catch(Exception e){
			throw e;
		}
	}
}
